package com.ssh.cp.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.stereotype.Repository;

/**
 * Servlet Filter implementation class LoginFilter
 */
@Repository
public class LoginFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp =(HttpServletResponse)response;
        HttpSession session = req.getSession();
           // 获得用户请求的URI
        String path = req.getRequestURI();
        //PrintWriter out = response.getWriter();
      
       
       String username = (String)session.getAttribute("username");

       if(req.getServletPath().endsWith(".css")|| req.getServletPath().endsWith(".js") ||req.getServletPath().endsWith(".jpg")||  req.getServletPath().endsWith(".png")) {
    	   chain.doFilter(req, resp);
       }else {
        if(path.indexOf("/register.html")>-1||path.indexOf("/index.jsp")>-1){
            chain.doFilter(req, resp);
            return;
        } else {
            if (username == null || "".equals(username)) {
           		
            	 resp.sendRedirect("index.jsp");
            	//request.getRequestDispatcher("/index.jsp").forward(request, response);
            } 
            else {
            	//chain.doFilter(req, resp);
            	chain.doFilter(request, response);
            }
        }
	}
	}
    
}
